#-*- coding: utf-8 -*-
import os
import sys
import logging
import optparse
import traceback

from selenose import __version__
from selenose.consts import LOGGER
from selenose.core import environ, startup, shutdown
from selenose.tools import set_options, storeurl, geturlpath

# Add an output
noselog = logging.getLogger(LOGGER)
# Keep info level and upper
noselog.setLevel(logging.INFO)
# Output on console
noselog.addHandler(logging.StreamHandler(sys.stdout))

# Get a logger
logger = logging.getLogger('%s.%s' % (LOGGER, __name__))

def run():
    '''Entry point'''
    _run(sys.argv)
    
def _run(argv):
    '''Process provided data'''
        
    # Get a parser
    parser = optparse.OptionParser()
    # Fill
    set_options(parser, binary=True)
    # Parse the options
    options = parser.parse_args(argv)[0]

    # Set configuration
    environ(options)

    # Start servers
    grid, djangos, server = startup(options, 1)
    
    # Get the URL
    storeurl(server.geturl())
    
    # Wait...
    try:
        # Log
        logger.info('\nSelenose version %s\nQuit selenose server with %s\n' % (__version__, (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C', ))
        # Wait...
        while True: raw_input()
    # Get CONTROL-C
    except (KeyboardInterrupt, EOFError): pass
    # Get errors
    except BaseException:
        # Stop grid
        logger.error(traceback.format_exc())
        
    # Stop servers
    shutdown(options.keep, grid, djangos, server)
    
    # Clean URL path
    os.remove(geturlpath())


    